Ext.define('appmod.controller.mycfs.Startup', {
    extend: 'Ext.app.Controller',

    views: [
    	'mycfs.DefaultListView',
		//'mycfs.MycfsForm',
		'mycfs.MycfsEditingForm'
    ],

	models : [
		'mycfs.Mycfs'
	],
	
    stores: [
		'mycfs.Paging'
	],	

    refs: [
		{ref: 'defaultListView',selector:'defaultlistview'},
		{ref: 'searchListView',selector:'defaultlistview searchfield'}
		

	],

    init: function() {

    	this.control({

			'defaultlistview menuitem[action=addMycfs]': {
				click:this.showAddMycfsForm
			},
			'defaultlistview menuitem[action=updateMycfs]': {
				click:this.showUpdateMycfsForm
			},
			'defaultlistview menuitem[action=deleteMycfs]': {
				click:this.showDeleteMycfsDialog
			},
			'mycfs-editingform': {
				addAttchment:{
					fn:this.addAttchment
				}
			}
			
						

    	});


    },
	
		
	loadInitComp : function() {
		var mainPanel = Ext.create('appmod.view.mycfs.DefaultListView' , {
			region : 'center',
			border:false,
			padding:'0 0 0 0'
		});
		return mainPanel;		
	},
	
	onLaunch:function(app) {
		
		var me = this;
		
		var defListView = me.getDefaultListView();
		var dsUserPange = me.getMycfsPagingStore();
		defListView.bindStore( dsUserPange );
		
	},
	
	// create dinfoe
	showAddMycfsForm : function() {
		var me = this;
		var win = null;
		// --- build new form ---
		if (!win) {
			win = new Ext.create('widget.window', {
				title : '新增知识点',
				closable : true,
				//closeAction:'hide',
				modal:true,
				width : 650,
				height : 480,
				layout: 'border',
				bodyStytle : 'padding : 5px',
				items:[{
					padding : 5,
					defaults: {
        				labelWidth:65
    				},
					xtype : 'mycfsform',
					region:'center'
				}],
				dockedItems: [{
				    xtype: 'toolbar',
				    dock: 'bottom',
				    ui: 'footer',
				    items: [
						'->',
				        {
            				text: '保 存',
							action:'addUserAccount'
        				},{
            				text: '重 置',
							action:'reset'
        				}
				    ]
				}]	
			});
		}
		
		// --- find form ---
		var form = win.down("mycfsform");

		var saveBtn = win.down('button[action="addUserAccount"]');
		saveBtn.on("click",me.saveNewMycfs , me , {
			window : win
		});
		
		var addAttchmentBtn = win.down('button[action="addAttachment"]');
		addAttchmentBtn.on("click", me.addAttchment , me , {
			window : win,
			formPanel : form
		});

		if ( !win.isVisible() ) {
			win.show();
		}
		
	},
	
	addAttchment:function(eOpts) {
		var me = this;
		
		var upWin = eOpts.window;
		var formPanel = eOpts.formPanel;
		var attchmentLayout = formPanel.down('fieldcontainer[name="attachmentLayout"]');
		var grid = formPanel.down('grid[name="attachmentGrid"]');
		//var data = grid.getStore().data;
		if(grid.getStore().data.length==0){
			var data = [{ 'name': eOpts.v,  "coller":"<a herf='#' >删除</a>"  }];
			var ds = Ext.create('Ext.data.Store', {
			    storeId:'simpsonsStore',
			    fields:['name', 'coller'],
			    data:data,
			    proxy: {
			        type: 'memory',
			        reader: {
			            type: 'json',
			            root: 'items'
			        }
			    }
			});
			grid.bindStore(ds);
			
		}else{
			grid.getStore().add({ 'name': eOpts.v,  "coller":"lisa@simpsons.com"  });
		}
		grid.addListener('cellclick', me.deleteAttachment);
		
	},
	
	saveNewMycfs:function(btn , event , eOpts) {
		var me = this;
		var listView = me.getDefaultListView();
		var dsUser = listView.getStore();

		var upWin = eOpts.window;
		
		var formPanel = upWin.down('mycfsform');
		var win = upWin;
		
		var form = formPanel.getForm();
		form.submit({
			url:'../../data/resource/provider/mycfs/submit_adding.json',
			success:function(form , action) {
				 // --- reflash store ---
				 win.close();
				 
				 dsUser.load();
				 
				 Ext.Msg.alert('成功', action.result.msg);
			},
			failure: function(form, action){
				switch (action.failureType) {
					case Ext.form.action.Action.CLIENT_INVALID:
						Ext.Msg.alert('失败', '表单里包含错误的信息');
						break;
					case Ext.form.action.Action.CONNECT_FAILURE:
						Ext.Msg.alert('失败', '服务器连接失败,请联系管理人员');
						break;
					case Ext.form.action.Action.SERVER_INVALID:
						Ext.Msg.alert('失败', action.result.msg);
				}
			}
		});
	},
	
	// create user info
	showUpdateMycfsForm : function() {

		var me = this;
		var defListView = me.getDefaultListView();	
		var selModel = defListView.getSelectionModel();
		var rec = selModel.getSelection();

		if (rec.length == 0) {
			Ext.MessageBox.show({
        		title: "提示",
        		msg: '请先选择一个帐号',
        		buttons: Ext.MessageBox.OK,
        		icon: Ext.MessageBox.WARNING
       		});
			return ;
		} else if (rec.length  > 1) {
			Ext.MessageBox.show({
        		title: "提示",
        		msg: '只能选择一个帐号',
        		buttons: Ext.MessageBox.OK,
        		icon: Ext.MessageBox.WARNING
       		});
			return ;
		}
		
		// --- build new form ---
		var win = null;
		if (!win) {
			win = new Ext.create('widget.window', {
				title : '知识点信息',
				mark:'mycfsform',
				closable : true,
				modal:true,
				//closeAction:'hide',
				width : 650,
				height : 380,
				layout: 'border',
				bodyStytle : 'padding : 5px',
				items:[{
					padding : 5,
					defaults: {
        				labelWidth:65
    				},
					xtype : 'mycfs.editingform',
					region:'center'
				}],
				dockedItems: [{
				    xtype: 'toolbar',
				    dock: 'bottom',
				    ui: 'footer',
				    items: [
						'->',
				        {
            				text: '保 存',
							action:'updateMycfs'
        				},{
            				text: '重 置',
							action:'reset'
        				}
				    ]
				}]	
			});
		}
		
		var formPanel = win.down("mycfs-editingform");

		var saveBtn = win.down('button[action="updateMycfs"]');
		saveBtn.on("click",me.saveUpdateMycfs , me , {
			window : win
		});
		
//		var addAttchmentBtn = win.down('button[action="addAttachment"]');
//		addAttchmentBtn.on("click", me.addAttchment , me , {
//			window : win,
//			formPanel : formPanel
//		});

		// --- init form data ---
		var form = formPanel.getForm();
		//var attachmentLayout = formPanel.down('fieldcontainer[name="attachmentLayout"]');
		var grid = formPanel.down('grid[name="attachmentGrid"]');
		grid.addListener('cellclick', me.deleteAttachment);
		
		form.load({
			params:{
				userId:rec[0].getId()
			},
			url: '../../data/resource/provider/mycfs/load_mycfs.json',
            waitMsg: '数据加载中',
			success: function(form , action) {

				var mycfs = action.result.data;
				var attachmentList = mycfs.attachments;
				
				var ds = Ext.create('Ext.data.Store', {
				    storeId:'simpsonsStore',
				    fields:['name', 'coller'],
				    data:attachmentList,
				    proxy: {
				        type: 'memory',
				        reader: {
				            type: 'json',
				            root: 'items'
				        }
				    }
				});
				grid.bindStore(ds);
		
				
		    } 	
		});
		

		
		if ( !win.isVisible() ) {
			win.show();			
		}		
	},
	
	deleteAttachment: function(AdviceGrid, b, columnIndex, e, a, rowIndex){
		//alert(rowIndex);
//				alert(AdviceGrid.getStore().getAt(0).get('name'));

				AdviceGrid.getStore().removeAt(rowIndex);
	},
	
	saveUpdateMycfs:function(btn , event , eOpts) {
		var me = this;
		var listView = me.getDefaultListView();
		var dsUser = listView.getStore();

		var upWin = eOpts.window;
		
		var formPanel = upWin.down('mycfs-editingform');
		var win = upWin;
		
		var form = formPanel.getForm();
		form.submit({
			url:'../../data/resource/provider/mycfs/submit_update.json',
			success:function(form , action) {
				 // --- reflash store ---
				 win.close();
				 
				 dsUser.load();
				 alert(action);
				 Ext.Msg.alert('成功', action.result.msg);
			},
			failure: function(form, action){
				switch (action.failureType) {
					case Ext.form.action.Action.CLIENT_INVALID:
						Ext.Msg.alert('失败', '表单里包含错误的信息');
						break;
					case Ext.form.action.Action.CONNECT_FAILURE:
						Ext.Msg.alert('失败', '服务器连接失败,请联系管理人员');
						break;
					case Ext.form.action.Action.SERVER_INVALID:
						Ext.Msg.alert('失败', action.result.msg);
				}
			}
		});
	},
	
	showDeleteMycfsDialog:function() {
		var me = this;
		
		var defListView = me.getDefaultListView();	
		var selModel = defListView.getSelectionModel();
		var rec = selModel.getSelection();


		if (rec.length == 0) {
			Ext.MessageBox.show({
        		title: "提示",
        		msg: '请先选择一个帐号',
        		buttons: Ext.MessageBox.OK,
        		icon: Ext.MessageBox.WARNING
       		});
			return ;
		}
		
		// --- select resource --
		var removeRecs = "";
		for (var i = 0 ; i < rec.length ; i++) {
			if (removeRecs.length != 0 ) {
				removeRecs += ",";
			}
			removeRecs += rec[i].get('title');
		}
		
		Ext.MessageBox.confirm('确认', '肯定要删除知识点: "'+removeRecs+'"?',me.confirmDeletedMycfs , me);
	},
	
	confirmDeletedMycfs:function(confirm , other) {

		var me = this;
		
		var defListView = me.getDefaultListView();	
		var selModel = defListView.getSelectionModel();
		var rec = selModel.getSelection();
		
		if (confirm == "no") {
			return;
		}

		var jsonObj = [];
		for (var i = 0 ; i < rec.length ; i++) {
			jsonObj.push(rec[i].getId());
		}

		
		// --- update record using ajax
		try {

			Ext.Ajax.request({
				url: '../../data/resource/provider/mycfs/submit_deleteall.json',
				method:'post',
				/*
				params:{
					'jsonData':Ext.encode(jsonObj)
				},
				*/
				jsonData:jsonObj,
				success: function(response, opts) {

					var listView = me.getDefaultListView();
					// --- update load ---
					listView.getStore().load();
										 
     				var obj = Ext.decode(response.responseText);
					 
					 // --- popup message ---
					Ext.MessageBox.show({
        				title: "提示",
        				msg: obj.msg,
        				buttons: Ext.MessageBox.OK,
        				icon: Ext.MessageBox.WARNING
       				});
					
					// --- reload ---

				},
				failure: function(response, opts) {
				
				}
			});

			
		} catch (e) {
			alert(e);
		}	
		
	}

	
	
});